import Request from './request';
import { getToken } from '@/utils/auth';
import { useAppid } from '@/hooks';

const request = new Request();
const { appName, platform } = tt.getSystemInfoSync();

request.setConfig({
  baseUrl: import.meta.env.VITE_BASE_URL,
  header: {
    'X-Platform': uni.getSystemInfoSync().platform,
  },
});

request.interceptor.request = async (options) => {
  options.header.Authorization = `Bearer ${getToken()}`;

  const { scene = '', query } = uni.getEnterOptionsSync();

  const params = {
    appid: useAppid(),
    scene,
    ...query,
    pkg: appName.toLowerCase() === 'douyin' ? 0 : 1, //0：抖音，1：抖音极速版
    os: platform === 'ios' ? 1 : 0, //0：Android，1：iOS
  };

  if ((options.method ?? 'get').toLowerCase() === 'get') {
    Object.assign(params, options.data);
  }

  const searchParams = new URLSearchParams(params);

  options.url += `${options.url.includes('?') ? '&' : '?'}${searchParams}`;
};

request.interceptor.response = async (res, options) => {
  if (res.statusCode >= 200 && res.statusCode < 300 && (res.data.success ?? true)) {
    return { ...res.data, response: res };
  }

  if (typeof res.data === 'string') {
    try {
      res.data = JSON.parse(res.data);
    } catch (e) {
      //
    }
  }

  switch (res.data.code) {
    case 401_001:
      uni.$emit('logout');
      break;
    default:
      if (!options.skipErrorHandler) {
        uni.showToast({ icon: 'none', title: res.data.message || '未知错误' });
      }
      break;
  }

  return Promise.reject({ response: res, options });
};

export default request;
